<template>
  <div>
    <el-radio-group v-model="activeIndex" @change="updateOrder">
      <el-radio-button value="0">全部订单</el-radio-button>
      <el-radio-button value="1">待接单</el-radio-button>
      <el-radio-button value="2">待完成</el-radio-button>
      <el-radio-button value="3">已完成</el-radio-button>
      <el-radio-button value="4">已取消</el-radio-button>
    </el-radio-group>
    <div style="padding: 20px; margin-top: 20px; background-color: #fff">
      <div class="flex-start-item">
        <div class="item flex-start-item">
          <p>订单号：</p>
          <el-input placeholder="请输入内容" class="input-form" v-model="numberSearch" />
        </div>
        <div class="item flex-start-item">
          <p>手机号：</p>
          <el-input placeholder="请选择" class="input-form" v-model="phoneSearch"></el-input>
        </div>
        <div class="item flex-start-item">
          <p>下单时间：</p>
          <el-date-picker
            v-model="timeFilter"
            type="daterange"
            range-separator="到"
            start-placeholder="Start date"
            end-placeholder="End date"
            @change="console.log(timeFilter)"
          />
        </div>
      </div>
      <div style="margin-top: 20px">
        <el-table
          :data="filterOrders"
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="number" label="订单号" width="150" align="center" />
          <el-table-column prop="status" label="订单状态" width="150" align="center">
            <template #default="scope">
              {{ orderStatus[scope.row.status] }}
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="150" align="center" />
          <el-table-column prop="orderTime" label="下单时间" width="220" align="center" />
          <el-table-column prop="price" label="实收金额" width="80" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button-group v-if="activeIndex == 0">
                <el-button plain size="small" @click="showOrder(scope.row.id)">查看</el-button>
              </el-button-group>

              <el-button-group v-else-if="activeIndex == 1">
                <el-button type="success" size="small" @click="takeOrder(scope.row.id)">接单</el-button>
                <el-button type="danger" plain size="small" @click="cancelOrder(scope.row.id)"
                  >拒接</el-button
                >
              </el-button-group>
              <el-button-group v-else-if="activeIndex == 2">
                <el-button type="success" size="small" @click="competeOrder(scope.row.id)">完成</el-button>
                <el-button type="danger" plain size="small" @click="cancelOrder(scope.row.id)"
                  >退款</el-button
                >
              </el-button-group>
              <el-button-group v-else-if="activeIndex == 3">
                <el-button plain size="small" @click="showOrder(scope.row.id)">查看</el-button>
              </el-button-group>
              <el-button-group v-else-if="activeIndex == 4">
                <el-button plain size="small" @click="showOrder(scope.row.id)">查看</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <div style="width: 100%; margin-top: 10px" class="flex-center-item">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalDishes"
            @current-change="handleCurrentChange(undefined)"
          />
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="订单详情" width="60%">
    <div class="header flex-space-between-item">
      <div class="left-head">
        <span>订单号：{{ orderInfo.number }}</span>
        <span class="badge">{{ orderStatus[orderInfo.status] }}</span>
      </div>
      <div class="right-head">下单时间：{{ orderInfo.orderTime }}</div>
    </div>
    <el-divider></el-divider>
    <div class="dialog-body">
      <p class="detail-item">用户名：{{ orderInfo.userDetail.name }}</p>
      <p class="detail-item">手机号：{{ orderInfo.userDetail.phone }}</p>
    </div>
    <el-divider></el-divider>
    <div class="dialog-body">
      <p class="detail-item">菜品名称：{{ orderInfo.orderDetail.name }}</p>
      <p class="detail-item">数量：{{ orderInfo.orderDetail.number }}</p>
      <p class="detail-item">价格：{{ orderInfo.orderDetail.price }}</p>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
const activeIndex = ref(0)

const totalDishes = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const indexToStatus = [0, 2, 3, 5, 6]
watch(activeIndex, () => handleCurrentChange(indexToStatus[activeIndex.value]))
watch(pageSize, () => handleCurrentChange(undefined))
function handleCurrentChange(status?: number) {
  orders.value = []
  console.log(status)
  let url = `/api/admin/order/conditionSearch?page=${currentPage.value}&pageSize=${pageSize.value}`
  if (status) {
    url += `&status=${status}`
  }
  fetch(url, {
    headers: headers
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.code === 1) {
        console.log(data.data)
        totalDishes.value = data.data.total
        data.data.records.forEach((item) => {
          orders.value.push({
            id: item.id,
            number: item.number,
            status: item.status,
            userId: item.userId,
            phone: item.phone,
            orderTime: item.orderTime,
            checkTime: item.orderTime,
            price: item.amount,
            payStatus: 0,
            amount: item.amount,
            updateTime: item.orderTime
          })
        })
      }
    })
}
const orders = ref([])
const orderStatus = ['', '待接单', '待接单', '制作中', '制作中', '已完成', '已取消']
const headers = new Headers({
  application: 'json',
  Authorization: sessionStorage.getItem('token')!,
  token: sessionStorage.getItem('token')!
})
const jsonHeaders = new Headers({
  application: 'json',
  Authorization: sessionStorage.getItem('token')!,
  token: sessionStorage.getItem('token')!,
  'Content-Type': 'application/json'
})
fetch('/api/admin/order/conditionSearch?page=1&pageSize=10', {
  headers: headers
})
  .then((res) => res.json())
  .then((data) => {
    if (data.code === 1) {
      console.log(data.data)
      totalDishes.value = data.data.total
      data.data.records.forEach((item) => {
        orders.value.push({
          id: item.id,
          number: item.number,
          status: item.status,
          userId: item.userId,
          phone: item.phone,
          orderTime: item.orderTime,
          checkTime: item.orderTime,
          price: item.amount,
          payStatus: 0,
          amount: item.amount,
          updateTime: item.orderTime
        })
      })
    }
  })
const numberSearch = ref('')
const phoneSearch = ref('')
const timeFilter = ref('')
const filterOrders = computed(() => {
  return orders.value.filter((order) => {
    if (numberSearch.value) {
      if (!order.number.includes(numberSearch.value)) return false
    }
    if (phoneSearch.value) {
      if (!order.phone.includes(phoneSearch.value)) return false
    }
    return true
  })
})
const dialogVisible = ref(false)
const orderInfo = reactive({
  number: 0,
  status: 0,
  orderTime: '',
  orderDetail: {
    name: '',
    number: 0,
    price: 0
  },
  userDetail: {
    name: '',
    phone: ''
  }
})
function showOrder(id: number) {
  fetch(`/api/admin/order/details/${id}`, {
    headers: jsonHeaders
  })
    .then((res) => res.json())
    .then((data) => {
      console.log(data.data)
      orderInfo.number = data.data.number
      orderInfo.status = data.data.status
      orderInfo.orderTime = data.data.orderTime
      orderInfo.orderDetail.name = data.data.orderDetailList[0].name
      orderInfo.orderDetail.number = data.data.orderDetailList[0].number
      orderInfo.orderDetail.price = data.data.orderDetailList[0].amount
      orderInfo.userDetail.name = data.data.consignee
      orderInfo.userDetail.phone = data.data.phone
    })
  dialogVisible.value = true
}
function cancelOrder(id: number) {
  fetch('/api/admin/order/cancel', {
    headers: jsonHeaders,
    method: 'PUT',
    body: JSON.stringify({
      id,
      reason: '我任意'
    })
  }).then(() => handleCurrentChange)
}
function takeOrder(id: number) {
  fetch('/api/admin/order/confirm', {
    headers: jsonHeaders,
    method: 'PUT',
    body: JSON.stringify({
      id
    })
  }).then(() => handleCurrentChange)
}
function competeOrder(id: number) {
  fetch(`/api/admin/order/complete/${id}`, {
    headers: jsonHeaders,
    method: 'PUT'
  }).then(() => handleCurrentChange)
}
</script>

<style scoped>
@import '@/assets/common.css';
p {
  text-wrap: nowrap;
}
.item {
  margin-right: 10px;
}

.input-form {
  width: 150px;
}
.header {
  font-size: 16px;
  margin-top: 20px;
}
.badge {
  background-color: #333333;
  color: #fff;
  border-radius: 5px;
  margin-left: 10px;
  padding:5px;
}
.dialog-body{
  display:flex;
  flex-direction:row;
  flex-wrap:wrap;

}
.detail-item{
  width:50%;
  margin:10px 0;
}
</style>
